<?php
/**
 * Created by PhpStorm
 * User: whh
 * Date: 2022/8/15
 * Time: 11:57
 */

namespace app\backstage\controller;


use app\backstage\logic\QaLogic;
use app\common\model\Auditor;
use app\common\model\AuditorEvent;
use app\common\model\ExamineNovel;
use app\common\model\IpLibrary;
use app\common\model\Ips;
use app\common\model\NovelClass;
use app\common\model\NovelFreq;
use app\common\model\NovelLabel;
use app\common\model\PaymentNumber;
use app\common\model\QuickApp as qa;
use app\common\model\QuickAppInfo;
use app\common\model\QuickShield;
use app\common\model\Subject;
use think\Controller;
use think\Db;

class QuickApp extends Controller
{

    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['getRandomExamineNovels']],
    ];

    /**
     * App
     * @return mixed
     * @Author: whh
     */
    public function index()
    {
        $subjects = Subject::getList();
        $this->assign('subjects', $subjects);
        return $this->fetch();
    }

    /**
     * App列表
     * @return \think\response\Json
     * @Author: whh
     */
    public function list()
    {
        $id = input('id');
        $name = input('name');
        $package_name = input('package_name');
        $subject_id = input('subject_id', 0);
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where = [];
        if ($id != '') {
            $where[] = ['id', '=', $id];
        }
        if ($name != '') {
            $where[] = ['name', 'like', "%$name%"];
        }
        if ($package_name != '') {
            $where[] = ['package_name', '=', $package_name];
        }
        if ($subject_id) {
            $where[] = ['subject_id', '=', $subject_id];
        }
        $list = Qa::getList($where, '*', 'id desc', $page, $limit, ['subject', 'info']);
        $count = Qa::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * App详情
     * @return mixed
     * @Author: whh
     */
    public function quickAppForm()
    {
        $id = input('id', 0);
        $qa = null;
        if ($id != 0) {
            $qa = Qa::get($id);
            if (!$qa) {
                return 'App不存在';
            }
        }

        $wxPays = PaymentNumber::where("pay_mode", 1)->select();
        $zfbPays = PaymentNumber::where("pay_mode", 2)->select();
        $subjects = Subject::getList();
        $this->assign('subjects', $subjects);
        $this->assign('qa', $qa);
        $this->assign('wxPays', $wxPays);
        $this->assign('zfbPays', $zfbPays);
        return $this->fetch();
    }


    /**
     * 修改客服
     * @Author: whh
     */
    public function changeContact()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.changeContact');
        if (true !== $result) {
            $this->error($result);
        }
        $ids = $params['ids'];
        foreach ($ids as $id) {
            $qa = Qa::get($id);
            if ($qa) {
                if ($qa->info) {
                    $qa->info->contact = $params['contact'];
                    $qa->together('info')->save();
                } else {
                    $qa->info()->save(['contact' => $params['contact']]);
                }
            }
        }
        $this->success();
    }


    /**
     * 设置App
     * @return string
     * @Author: whh
     */
    public function setQuickApp()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setQuickApp');
        if (true !== $result) {
            $this->error($result);
        }
        $logic = new QaLogic();
        return $logic->setQuickApp($params);
    }


    /**
     * 设置App页面
     * @return array|bool|mixed|string|true
     * @Author: whh
     */
    public function sendConfigForm()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.sendConfigForm');
        if (true !== $result) {
            return $result;
        }
        $qa = Qa::get($params['id']);
        if (!$qa) {
            return 'App不存在';
        }
        $this->assign('qa', $qa);
        $send_config = $qa->info->send_config;
        $this->assign('send_config', $send_config);
        if ($params['mobile_brand'] == 'show') {
            return $this->fetch("send_config_show", ['jsonStr' => $qa->info->getData('send_config')]);
        }
        return $this->fetch("send_{$params['mobile_brand']}_form");
    }


    /**
     * 主体
     * @return mixed
     * @Author: whh
     */
    public function subject()
    {
        return $this->fetch();
    }


    /**
     * 主体列表
     * @return \think\response\Json
     * @Author: whh
     */
    public function subjectList()
    {
        $keyword = trim(input('keyword'));
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where = [];
        if ($keyword != '') {
            $where[] = ['id|subject_name', '=', $keyword];
        }
        $list = Subject::getList($where, '*', 'id desc', $page, $limit);
        $count = Subject::getCount($where);
        return sucJson($list, $count);
    }

    /**
     * 主体详情
     * @return mixed|string
     * @Author: whh
     */
    public function subjectForm()
    {

        $id = input('id', 0);
        $subject = null;
        if ($id != 0) {
            $subject = Subject::get($id);
            if (!$subject) {
                return '主体不存在';
            }
        }
        $this->assign('subject', $subject);
        return $this->fetch();
    }

    /**
     * 设置主体
     * @Author: whh
     */
    public function setSubject()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setSubject');
        if (true !== $result) {
            $this->error($result);
        }
        if (isset($params['id']) && $params['id']) {
            $subject = Subject::get($params['id']);
            if (!$subject) {
                $this->error('主体不存在');
            }
            $subject->save($params);
        } else {
            $subject = new Subject();
            $subject->save($params);
        }
        $this->success();
    }


    /**
     * 删除主体
     * @throws \Exception
     * @Author: whh
     */
    public function delSubject()
    {
        $id = input('id', 0);
        $subject = Subject::get($id);
        if (!$subject) {
            $this->error('主体不存在');
        }
        $subject->delete();
        $this->success();
    }


    /**
     * 设置推送参数
     * @Author: whh
     */
    public function setSendConfig()
    {
        $params = $this->request->post();
        $result = $this->validate($params, 'app\backstage\validate\QaSendConfigValidate.setSendConfig');
        if (true !== $result) {
            $this->error($result);
        }
        $mobile_brand = $params['mobile_brand'];
        $result = $this->validate($params, 'app\backstage\validate\QaSendConfigValidate.' . $mobile_brand);
        if (true !== $result) {
            $this->error($result);
        }
        $info = QuickAppInfo::where('quick_id', $params['id'])->find();
        if (!$info) {
            $this->error('App附属信息不存在');
        }
        if ($info->send_config == null) {
            $send_config = QuickAppInfo::initSendConfig();
        } else {
            $send_config = $info->send_config;
        }
        unset($params['id']);
        unset($params['mobile_brand']);
        if (isset($params['appId'])) {
            $params['appId'] = intval($params['appId']);
        }
        $send_config[$mobile_brand] = $params;
        $info->send_config = $send_config;
        $info->save();
        $this->success();
    }


    /**
     * 单元格编辑备注
     * @Author: whh
     */
    public function editRemarks()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.editRemarks');
        if (true !== $result) {
            $this->error($result);
        }
        $manager = \app\common\model\QuickAppInfo::get($params['id']);
        $manager->remarks = $params['remarks'];
        $manager->save();
        $this->success();
    }

    /**
     * 机型
     * @return mixed
     */
    public function auditEvent()
    {
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        return $this->fetch();
    }


    /**
     * 事件列表
     * @return \think\response\Json
     * @Author: whh
     */
    public function auditEventList()
    {
        $quick_id = input('quick_id');
        $provider = input('provider');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where[] = ['delete_time', '=', 0];
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($provider != '') {
            $where[] = ['provider', '=', $provider];
        }
        $list = AuditorEvent::getList($where, '*', 'id desc', $page, $limit, ['quick_app']);
        $count = AuditorEvent::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * 审核员列表
     * @return \think\response\Json
     * @Author: whh
     */
    public function auditorList()
    {
        $userId = input('userId');
        $event_id = input('event_id');
        $quick_id = input('quick_id');
        $provider = input('provider');
        $page = input('page', 1);
        $limit = input('limit', 10);
        $where = [];
        if ($userId != '') {
            $where[] = ['userId', '=', $userId];
        }
        if ($event_id != '') {
            $where[] = ['event_id', '=', $event_id];
        }
        if ($quick_id != '') {
            $where[] = ['quick_id', '=', $quick_id];
        }
        if ($provider != '') {
            $where[] = ['provider', '=', $provider];
        }
        $list = Auditor::getList($where, '*', 'id desc', $page, $limit, ['quick_app']);
        $count = Auditor::getCount($where);
        return sucJson($list, $count);
    }


    /**
     * 设置审核事件
     * @return mixed|\think\response\Json
     */
    public function addAuditEvent()
    {
        if (request()->isAjax()) {
            $params = $this->request->param();
            $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.addAuditEvent');
            if (true !== $result) {
                $this->error($result);
            }
            $model = new AuditorEvent();
            $model->allowField(true)->save($params);
            $this->success();
        }
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        return $this->fetch();
    }

    /**
     * 删除审核事件
     */
    public function delAuditEvent()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.delAuditEvent');
        if (true !== $result) {
            $this->error($result);
        }
        AuditorEvent::destroy($params['id']);//软删除
        $this->success();
    }

    /**
     * 设置审核字段值
     */
    public function editAuditEventField()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.editAuditEventField');
        if (true !== $result) {
            $this->error($result);
        }
        $event = AuditorEvent::get($params['id']);
        if ($params['field'] == 'desc') {
            $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.desc');
            if (true !== $result) {
                $this->error($result);
            }
            $event->desc = $params['value'];
        } elseif ($params['field'] == 'status') {
            $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.status');
            if (true !== $result) {
                $this->error($result);
            }
            $event->status = $params['value'];
        } else {
            $this->error('参数异常');
        }
        $event->save();
        $this->success();
    }

    /**
     * 修改审核员状态
     */
    public function setAuditorStatus()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setAuditorStatus');
        if (true !== $result) {
            $this->error($result);
        }
        $auditor = Auditor::get($params['id']);
        if (!$auditor) {
            $this->error('用户不存在');
        }
        $auditor->status = $params['status'];
        $auditor->save();
        $this->success();
    }


    /**
     * 审核书列表
     * @return mixed|\think\response\Json
     */
    public function examineNovels()
    {
//        $list = ExamineNovel::with(['novel', 'quick_app'])->order("id desc")->select();
//        foreach ($list as $v){
//            if (!$v->novel){
//                ExamineNovel::where("id",$v->id)->delete();
//            }
//        }
        if (request()->isAjax()) {
            $novelId = input('novel_id');
            $quickId = input('quick_id');
            $page = input('page', 1);
            $limit = input('limit', 10);
            $where = [];
            if ($novelId != '') {
                $where[] = ['novel_id', '=', $novelId];
            }
            if ($quickId != '') {
                $where[] = ['quick_id', '=', $quickId];
            }

            $list = ExamineNovel::where($where)->with(['novel', 'quick_app'])->order("id desc")->page($page, $limit)->select();
            foreach ($list as $k => $v) {
                if ($v->novel){
                    $v->novel->freq;
                    $v->novel->novel_class;
                }
            }
            $count = ExamineNovel::where($where)->count();
            return sucJson($list, $count);
        }

        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        return $this->fetch();
    }

    /**
     * 添加审核书籍
     */
    public function addExamineNovel()
    {
        $novelIds = input('novel_ids');
        $novelIds = explode(',', $novelIds);
        $quickId = input('quick_id');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.addExamineNovel');
        if (true !== $result) {
            $this->error($result);
        }
        $qa = \app\common\model\QuickApp::get($quickId);
        if (!$qa) {
            $this->error('App不存在');
        }
        $where[] = ['quick_id', '=', $params['quick_id']];
        $haveNIds = ExamineNovel::where($where)->column('novel_id');
        $diff = array_diff($novelIds, $haveNIds);//得到没有的值
        $saveIds = \app\common\model\Novel::where("id", "in", $diff)->column('id');
        $saveArr = [];
        foreach ($saveIds as $id) {
            $saveArr[] = [
                'quick_id' => $quickId,
                'novel_id' => $id,
            ];
        }
        $count = count($saveIds);
        ExamineNovel::insertAll($saveArr);
        if ($count > 0) {
            $this->success("成功添加{$count}本");
        } else {
            $this->error("小说不存在或已添加");
        }
    }

    /**
     * 删除审核书
     * @return \think\response\Json
     */
    public function delExamineNovel()
    {
        $ids = input('ids');
        if ($ids) {
            ExamineNovel::where("id", "in", $ids)->delete();
        }
        ExamineNovel::destroy($ids);
        return sucJson();
    }

    /**
     * 获取随机书
     * @return \think\response\Json
     */
    public function getRandomExamineNovels()
    {
        $novelIds = ExamineNovel::column('novel_id');
        $where[] = ['scale', '=', 'C'];
        $where[] = ['id', 'not in', $novelIds];
        $where[] = ['in_shelf', '=', 1];
        $list = \app\common\model\Novel::where($where)->orderRand()->limit(20)->column('id');
        $list = implode(',', $list);
        return sucJson($list);
    }


    public function ipLibrary()
    {
        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        return $this->fetch();
    }

    /**
     * App屏蔽规则
     * @return mixed
     */
    public function blockingRules()
    {
        $type = input('type',1);
        $ipL = IpLibrary::field("id,title")->select();
        $this->assign('ipL', $ipL);
        if ($type == 1){
            $id = input('id');
            $qa = \app\common\model\QuickApp::get($id);
            if (!$qa) {
                $this->error('参数异常');
            }
            $info = $qa->shield;
            $novel = null;
            if ($info) {
                $novel = \app\common\model\Novel::get($info->link_replace_nid);
            }
            $this->assign('info', $info);
            $this->assign('id', $id);
            $this->assign('novel', $novel);
            return $this->fetch();
        }else{
            $ids = input('ids');
            $this->assign('ids', $ids);
            return $this->fetch('blocking_rules_pl');
        }
    }

    /**
     * 设置屏蔽规则
     * @return \think\response\Json
     */
    public function setBlockRule()
    {
        $type = input('type');
        if ($type == 2){
            return $this->setBlockRulePl();
        }
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setBlockRule');
        if (true !== $result) {
            $this->error($result);
        }
        $shield = QuickShield::get($params['id']);
        if (!$shield) {
            $shield = new QuickShield();
        }
        $novel = \app\common\model\Novel::get($params['link_replace_nid']);
        if (!$novel) {
            $this->error('请输入正确的链接替换书籍');
        }
        if ($novel->scale != 'C') {
            $this->error('替换书尺度必须为C级');
        }
        $shield->quick_id = $params['id'];
        $shield->link_replace_nid = $params['link_replace_nid'];
        $shield->switch = isset($params['switch']) && $params['switch'] == 1 ? 1 : 0;
        $shield->area = $params['area'];
        if (isset($params['iplib_ids'])) {
            $shield->iplib_ids = implode(',', $params['iplib_ids']);
        } else {
            $shield->iplib_ids = '';
        }
        if (isset($params['white_uids'])) {
            $shield->white_uids = $params['white_uids'];
        }
        if (isset($params['open_hour'])) {
            $shield->open_hour = implode(',', $params['open_hour']);
        } else {
            $shield->open_hour = '';
        }
        $shield->save();
        return sucJson();
    }

    /**
     * 批量设置屏蔽
     * @return \think\response\Json
     */
    public function setBlockRulePl(){
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setBlockRulePl');
        if (true !== $result) {
            $this->error($result);
        }
        $novel = \app\common\model\Novel::get($params['link_replace_nid']);
        if (!$novel) {
            $this->error('请输入正确的链接替换书籍');
        }
        if ($novel->scale != 'C') {
            $this->error('替换书尺度必须为C级');
        }
        $qids = explode(',',$params['qids']);
        foreach ($qids as $qid) {
            $shield = QuickShield::get($qid);
            if (!$shield) {
                $shield = new QuickShield();
            }
            $shield->quick_id = $qid;
            $shield->link_replace_nid = $params['link_replace_nid'];
            $shield->switch = isset($params['switch']) && $params['switch'] == 1 ? 1 : 0;
            $shield->area = $params['area'];
            if (isset($params['iplib_ids'])) {
                $shield->iplib_ids = implode(',', $params['iplib_ids']);
            } else {
                $shield->iplib_ids = '';
            }
            if (isset($params['open_hour'])) {
                $shield->open_hour = implode(',', $params['open_hour']);
            } else {
                $shield->open_hour = '';
            }
            $shield->save();
        }
        return sucJson();
    }

    /**
     * 库列表
     * @return \think\response\Json
     */
    public function ipLibs()
    {
        $list = IpLibrary::all();
        return sucJson($list);
    }

    /**
     * 设置ip库
     * @return \think\response\Json
     */
    public function setIpLib()
    {
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.setIpLib');
        if (true !== $result) {
            $this->error($result);
        }
        $id = input('id');
        if ($id) {
            $model = IpLibrary::get($id);
        } else {
            $model = new IpLibrary();
        }
        if (!$model) {
            $this->error('参数异常');
        }
        $model->title = $params['title'];
        $model->save();
        return sucJson();
    }

    /**
     * ip
     * @return mixed|\think\response\Json
     */
    public function libIps()
    {
        $id = input('id');
        if (request()->isAjax()) {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $lib_id = input('lib_id');
            $where = [];
            if ($lib_id != '') {
                $where[] = ['lib_id', '=', $lib_id];
            }
            $list = Ips::getList($where, "*", 'id desc', $page, $limit);
            $count = Ips::getCount($where);
            return sucJson($list, $count);
        }
        $lib = IpLibrary::get($id);
        if (!$lib) {
            $this->error('参数异常');
        }
        $this->assign('lib', $lib);
        return $this->fetch();
    }

    /**
     * 删除ip
     * @return \think\response\Json
     * @throws \Exception
     */
    public function delLibIp()
    {
        $id = input('id');
        Ips::where("id", $id)->delete();
        return sucJson();
    }


    /**
     * 添加ip
     * @throws \Exception
     */
    public function addLibIp()
    {
        $ips = input('ips');
        $libId = input('lib_id');
        $params = $this->request->param();
        $result = $this->validate($params, 'app\backstage\validate\QuickAppValidate.addLibIp');
        if (true !== $result) {
            $this->error($result);
        }
        $ipArr = array_unique(explode(',', $ips));
        $data = [];
        foreach ($ipArr as $k => $v) {
            $where = [];
            $where[] = ['lib_id', '=', $libId];
            $where[] = ['ip', '=', $v];
            $flag = Ips::where($where)->find();
            if (!$flag) {
                $data[$k]['lib_id'] = $libId;
                $data[$k]['ip'] = $v;
            }
        }
        $model = new Ips();
        $count = $model->insertAll($data);
        $count = $count ? $count : 0;
        $this->success("共添加{$count}条ip");
    }

    /**
     * 协议地址
     * @return \think\response\Json
     */
    public function getContract()
    {
        $id = input('id');
        $qa = \app\common\model\QuickApp::get($id);
        if (!$qa) {
            $this->error('App不存在');
        }
        if (!$qa->subject) {
            $this->error('请先绑定主体信息');
        }
        if (!$qa->subject->domain) {
            $this->error('请先绑定主体接口域名');
        }
        $data['privacy'] = $qa->subject->domain . "/contract/information?type=privacy&x-quick-package=" . $qa->package_name;
        $data['user'] = $qa->subject->domain . "/contract/information?type=user&x-quick-package=" . $qa->package_name;
        $data['vip'] = $qa->subject->domain . "/contract/information?type=vip&x-quick-package=" . $qa->package_name;
        return sucJson($data);
    }
}